package com.lianxi.util;


import cn.hutool.extra.ftp.Ftp;


import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.UUID;

/**
 * @author：张高飞
 * @since： 2021/12/29 16:27
 */
public class FtpUtil {




    private static final String[] SERVERS_ARRAY = ResourcesUtils.getFTPConfig().split(",");

    public static String getUploadPath(MultipartFile mf){
        return "workorder/files/"+DateUtil.format(new Date(),"yyyy-MM-dd")+"/"+ UUID.randomUUID().toString().replace("-","");
    }

    public static void upload(String remotePath,String fileName, InputStream inputStream) {
        try {
            //匿名登录（无需帐号密码的FTP服务器）
            Ftp ftp = new Ftp(SERVERS_ARRAY[0],21,SERVERS_ARRAY[1],SERVERS_ARRAY[2]);
            //上传本地文件
            ftp.upload(remotePath,fileName,inputStream);
            //关闭连接
            ftp.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void remove(String remoteFile) {
        try {
            //匿名登录（无需帐号密码的FTP服务器）
            Ftp ftp = new Ftp(SERVERS_ARRAY[0],21,SERVERS_ARRAY[1],SERVERS_ARRAY[2]);
            //上传本地文件
            ftp.delFile(remoteFile);
            //关闭连接
            ftp.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void download(String remotePath,String fileName, OutputStream outputStream) {
        try {
            //匿名登录（无需帐号密码的FTP服务器）
            Ftp ftp = new Ftp(SERVERS_ARRAY[0],21,SERVERS_ARRAY[1],SERVERS_ARRAY[2]);
            //下载
            ftp.download(remotePath,fileName,outputStream);
            //关闭连接
            ftp.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
